package com.estun.backroundManagementService.modules.product.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.estun.backroundManagementService.domain.BasePageRequest;
import com.estun.backroundManagementService.domain.BaseResponse;
import com.estun.backroundManagementService.modules.product.model.Product;
import com.estun.backroundManagementService.modules.product.model.ProductStationTime;
import com.estun.backroundManagementService.modules.product.model.excel.ProductExportExcel;
import com.estun.backroundManagementService.modules.product.model.res.ProductRecord;
import com.estun.backroundManagementService.modules.product.request.ProductRequest;
import com.estun.backroundManagementService.modules.product.service.ProductService;
import com.estun.backroundManagementService.modules.product.service.ProductStationTimeService;
import com.estun.backroundManagementService.utils.QueryWrapperUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 产品表 前端控制器
 * </p>
 *
 * @author machine
 * @since 2023-02-14
 */
@RestController
@Api(tags = "ProductController", description = "产品管理")
@RequestMapping("/product")
@AllArgsConstructor
public class ProductController {

    private final ProductService productService;

    private final ProductStationTimeService productStationTimeService;

    @ApiOperation(value = "产品列表查询(new)")
    @PostMapping("/page")
    public BaseResponse pushWorkOrder(@RequestBody BasePageRequest<Product> pageRequest) {
        Page<Product> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        Product query = pageRequest.getQuery();
        QueryWrapper<Product> queryWrapper = QueryWrapperUtil.buildQueryWrapper(query);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.between(query.getBeginTime() != null && query.getEndTime() != null, "create_time", query.getBeginTime(), query.getEndTime());
        Page<Product> page1 = productService.page(page, queryWrapper);
        return BaseResponse.success(page1);
    }

    @ApiOperation(value = "产品列表导出")
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody BasePageRequest<Product> pageRequest) throws IOException {
        Product query = pageRequest.getQuery();
        QueryWrapper<Product> queryWrapper = QueryWrapperUtil.buildQueryWrapper(query);
        queryWrapper.between(query.getBeginTime() != null && query.getEndTime() != null, "create_time", query.getBeginTime(), query.getEndTime());
        queryWrapper.orderByDesc("create_time");
        List<Product> list = productService.list(queryWrapper);
        List<ProductExportExcel> productExportExcels = BeanUtil.copyToList(list, ProductExportExcel.class);

        // 设置响应类型和文件名
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("产品列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 使用easyexcel写入数据到输出流
        EasyExcel.write(response.getOutputStream(), ProductExportExcel.class).sheet("产品数据").doWrite(productExportExcels);
    }

    @ApiOperation(value = "产品产能统计")
    @GetMapping("/getProductStat")
    public BaseResponse getProductStat(String currentDate) {
        return BaseResponse.success(productService.getProductStat(currentDate));
    }

    @GetMapping("/getByProductId/{productNo}")
    public BaseResponse getByProductId(@PathVariable String productNo) {
        return BaseResponse.success(productService.getOne(new QueryWrapper<Product>()
                .eq("product_no", productNo)
                .ne("type", 3)));
    }

    @GetMapping("/offlineCheck/{productNo}")
    public BaseResponse offlineCheck(@PathVariable String productNo) {
        ProductRecord productRecord = productService.getProductByProductNo(productNo);
        Product test = productRecord.getTest();

        List<ProductStationTime> productStationTimeList = new ArrayList<>();

        //如果是测试线产品
        if (test != null) {
            Long productId = test.getId();
            productStationTimeList = productStationTimeService.list(new QueryWrapper<ProductStationTime>().eq("product_id", productId));
        } else {
            Product up = productRecord.getUp();
            Product lower = productRecord.getLower();
            if (up == null) {
                return BaseResponse.error("缺少上油路板产品数据");
            }
            if (lower == null) {
                return BaseResponse.error("缺少下油路板产品数据");
            }
            List<ProductStationTime> upStationTimeList = productStationTimeService.getByProductId(up.getId());
            List<ProductStationTime> lowerStationTimeList = productStationTimeService.getByProductId(lower.getId());
            productStationTimeList.addAll(upStationTimeList);
            productStationTimeList.addAll(lowerStationTimeList);
        }
        StringBuilder errorMes = new StringBuilder();
        for (ProductStationTime productStationTime : productStationTimeList) {
            if (productStationTime.getStatus() == null || productStationTime.getStatus() != 1) {
                errorMes.append(productStationTime.getStationId()).append(",");
            }
        }
        if (StringUtils.isNotBlank(errorMes.toString())) {
            return BaseResponse.error(errorMes + "失败");
        }
        return BaseResponse.success();
    }


    @ApiOperation(value = "产品产能按周期统计")
    @PostMapping("/getProductStatByCycle")
    public BaseResponse getProductStatByCycle(@RequestBody ProductRequest productRequest) {
        return BaseResponse.success(productService.pageProductStatByCycle(productRequest));
    }


}

